<script setup>
import { Edit, Delete } from "@element-plus/icons-vue";
import {Delta, QuillEditor} from "@vueup/vue-quill";
import "@vueup/vue-quill/dist/vue-quill.snow.css";
import {CategoryList} from "@/api/category.js";
import {ref, getCurrentInstance, nextTick} from "vue";
import {
  ArticleList,
  ArticleUpdate,
  ArticleAdd,
  ArticleDelete,
} from "@/api/article.js";
import {ElMessage, ElMessageBox} from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { userTokenStore } from "@/store/userTokenStore.js";
//控制抽屉是否显示
const visibleDrawer = ref(false);
//添加表单数据模型
const articleModel = ref({
  title: "",
  categoryId: "",
  coverImg: "",
  content: "",
  state: "",
});
const store = userTokenStore();
//笔记上传成功与否
const FileUplad = (result) => {
  articleModel.value.coverImg = result.data;
  console.log(result.data);
  console.log("上传成功");
  ElMessage.success("上传成功！");
};
const handleUploadError = (error) => {
  console.log(error);
  console.log("上传失败");
  ElMessage.error("上传失败");
};

//文章分类数据模型
const categorys = ref([
  {
    id: 3,
    categoryName: "美食",
    categoryAlias: "my",
    createTime: "2023-09-02 12:06:59",
    updateTime: "2023-09-02 12:06:59",
  },
  {
    id: 4,
    categoryName: "娱乐",
    categoryAlias: "yl",
    createTime: "2023-09-02 12:08:16",
    updateTime: "2023-09-02 12:08:16",
  },
  {
    id: 5,
    categoryName: "军事",
    categoryAlias: "js",
    createTime: "2023-09-02 12:08:33",
    updateTime: "2023-09-02 12:08:33",
  },
]);

//获取文章分类
const GetList = async () => {
  const result = await CategoryList();
  categorys.value = result.data;
  categorys.value.unshift({
    id: 0,
    categoryName: "所有",
  });
};

GetList();

//用户搜索时选中的分类id
const categoryId = ref("");

//用户搜索时选中的发布状态
const state = ref("");

//文章列表数据模型
const articles = ref([
  /* {
    "id": 5,
    "title": "陕西旅游攻略",
    "content": "兵马俑,华清池,法门寺,华山...爱去哪去哪...",
    "coverImg": "https://big-event-gwd.oss-cn-beijing.aliyuncs.com/9bf1cf5b-1420-4c1b-91ad-e0f4631cbed4.png",
    "state": "草稿",
    "categoryId": 2,
    "createTime": "2023-09-03 11:55:30",
    "updateTime": "2023-09-03 11:55:30"
  },
  {
    "id": 5,
    "title": "陕西旅游攻略",
    "content": "兵马俑,华清池,法门寺,华山...爱去哪去哪...",
    "coverImg": "https://big-event-gwd.oss-cn-beijing.aliyuncs.com/9bf1cf5b-1420-4c1b-91ad-e0f4631cbed4.png",
    "state": "草稿",
    "categoryId": 2,
    "createTime": "2023-09-03 11:55:30",
    "updateTime": "2023-09-03 11:55:30"
  },
  {
    "id": 5,
    "title": "陕西旅游攻略",
    "content": "兵马俑,华清池,法门寺,华山...爱去哪去哪...",
    "coverImg": "https://big-event-gwd.oss-cn-beijing.aliyuncs.com/9bf1cf5b-1420-4c1b-91ad-e0f4631cbed4.png",
    "state": "草稿",
    "categoryId": 2,
    "createTime": "2023-09-03 11:55:30",
    "updateTime": "2023-09-03 11:55:30"
  },*/
]);
//分页条数据模型
const pageNum = ref(1); //当前页
const total = ref(20); //总条数
const pageSize = ref(3); //每页条数
const typeOfMethod = ref("添加笔记");
//搜索功能
const GetListForArticle = async (message) => {
  const params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    categoryId: categoryId
      ? categoryId.value === "" || categoryId.value === 0
        ? null
        : categoryId.value
      : null,
    state: state
      ? state.value === "" || state.value === "所有"
        ? null
        : state.value
      : null,
  };
  const result = await ArticleList(params);
  articles.value = result.data.items;
  total.value = result.data.total;
  if (message !== "") ElMessage.success(message);
};
GetListForArticle("搜索成功！");
const quillEditorRef = ref(null)
//页面关闭与model清空
const clear = async () => {
  visibleDrawer.value = false;
  articleModel.value = {
    title: "",
    categoryId: "",
    coverImg: "",
    content: "",
    state: "",
  };
  // 直接使用 ref 来访问组件实例 todo 这里有一个bug，文章内容还是会出现的页面当中，待解决
  // 添加重试机制，确保编辑器已经初始化
  let retryCount = 0;
  const maxRetries = 5;
  const retryInterval = 200; // 重试间隔 200 毫秒

  const tryClearEditor = async () => {
    await nextTick();
    const editor = quillEditorRef.value;
    if (editor && editor.quill) {
      editor.quill.setContents([{ insert: '\n' }]);
      articleModel.value.content = "";

      const text = editor.quill.getText(0, 10);
      console.log("text: ", text);
      console.log('articleModel: ', articleModel.value);
    } else if (retryCount < maxRetries) {
      retryCount++;
      setTimeout(tryClearEditor, retryInterval);
    } else {
      console.error("Quill editor not initialized after multiple attempts");
    }
  };

  tryClearEditor();
};
//上传笔记
const AddForArticle = async () => {
  await ArticleAdd(articleModel.value);
  await clear();
  ElMessage.success("上传成功！");
  await GetListForArticle("");
};

//展示修改的文章信息;
const showUpdateArticle = (row) => {
  visibleDrawer.value = true;
  typeOfMethod.value = "修改笔记";
  articleModel.value.state = row.state;
  articleModel.value.content = row.content;
  articleModel.value.title = row.title;
  articleModel.value.coverImg = row.coverImg;
  articleModel.value.categoryId = row.categoryId;
  articleModel.value.id = row.id;
};
//修改文章接口;
const UpdateForArticle = async () => {
  await ArticleUpdate(articleModel.value);
  await GetListForArticle("修改成功！");
  clear();
};
//删除文章接口
const DeleteForArticle = async (row)=>{
  ElMessageBox.confirm(
      '此操作将删除该笔记，是否确认删除？',
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        const params = {
          id : row.id
        };
        await ArticleDelete(params);
        await GetListForArticle("删除成功!");
        clear();
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '删除取消!',
        })
      })
}
//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
  pageSize.value = size;
  GetListForArticle("页面条数变化");
};
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  pageNum.value = num;
  GetListForArticle("页码变化");
};
</script>
<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>笔记管理</span>
        <div class="extra">
          <el-button
            type="primary"
            @click="
              clear();
              visibleDrawer = true;
              typeOfMethod = '添加笔记';
            "
            >添加笔记</el-button
          >
        </div>
      </div>
    </template>
    <!-- 搜索表单 -->
    <el-form inline>
      <el-form-item label="笔记分类：">
        <el-select
          placeholder="请选择"
          v-model="categoryId"
          style="width: 240px"
        >
          <el-option
            v-for="c in categorys"
            :key="c.id"
            :label="c.categoryName"
            :value="c.id"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="发布状态：">
        <el-select placeholder="请选择" v-model="state" style="width: 240px">
          <el-option label="所有" value="所有"></el-option>
          <el-option label="已回顾" value="已回顾"></el-option>
          <el-option label="待回顾" value="待回顾"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="GetListForArticle('搜索成功!')"
          >搜索</el-button
        >
        <el-button
          @click="
            categoryId = '';
            state = '';
            GetListForArticle('重置成功!');
          "
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 文章列表 -->
    <el-table :data="articles" style="width: 100%">
      <el-table-column
          type="index"
          label="序号"
          width="50"
      ></el-table-column>
      <el-table-column
        label="笔记标题"
        width="400"
        prop="title"
      ></el-table-column>
      <el-table-column label="分类" prop="categoryName"></el-table-column>
      <el-table-column label="发表时间" prop="createTime"> </el-table-column>
      <el-table-column label="状态" prop="state"></el-table-column>
      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button
              :icon = Edit
              circle
            plain
            type="primary"
            @click="showUpdateArticle(row)" >  </el-button>
          <el-button
            :icon="Delete"
            circle
            plain
            type="danger"
            @click="DeleteForArticle(row)"
          ></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
    <!-- 分页条 -->
    <el-pagination
      v-model:current-page="pageNum"
      v-model:page-size="pageSize"
      :page-sizes="[3, 5, 10, 15]"
      layout="jumper, total, sizes, prev, pager, next"
      background
      :total="total"
      @size-change="onSizeChange"
      @current-change="onCurrentChange"
      style="margin-top: 20px; justify-content: flex-end"
    />
  </el-card>
  <!-- 抽屉 -->
  <el-drawer
    v-model="visibleDrawer"
    :title= "typeOfMethod"
    direction="rtl"
    size="90%"
    @close = "clear"
  >
    <!-- 添加笔记表单 -->
    <el-form :model="articleModel" label-width="100px">
      <el-form-item label="笔记标题">
        <el-input
          v-model="articleModel.title"
          placeholder="请输入标题"
        ></el-input>
      </el-form-item>
      <el-form-item label="笔记分类">
        <el-select placeholder="请选择" v-model="articleModel.categoryId">
          <el-option
            v-for="c in categorys"
            :key="c.id"
            :label="c.categoryName"
            :value="c.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="笔记封面">
        <el-upload
          class="avatar-uploader"
          :auto-upload="true"
          :show-file-list="false"
          action="/api/file/upload"
          name="file"
          :headers="{ Authorization: store.token }"
          :on-success="FileUplad"
          :on-error="handleUploadError"
        >
          <img
            v-if="articleModel.coverImg"
            :src="articleModel.coverImg"
            class="avatar"
            :alt = "articleModel.coverImg"
          />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="笔记内容">
        <div class="editor">
          <quill-editor
            theme="snow"
            v-model:content="articleModel.content"
            contentType="html"
            :ref="quillEditorRef"
          >
          </quill-editor>
        </div>
      </el-form-item>
      <el-form-item label="笔记状态">
        <el-radio-group v-model="articleModel.state">
          <el-radio value="已回顾">已回顾</el-radio>
          <el-radio value="待回顾">待回顾</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="
            typeOfMethod === '添加笔记' ? AddForArticle() : UpdateForArticle()
          "
          >上传</el-button
        >
        <el-button type="info" @click="clear">取消</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>
<style lang="scss" scoped>
/* 现代化样式增强 */
.el-drawer {
  border-radius: 18px 18px 0 0;
  box-shadow: 0 8px 32px 0 rgba(80, 120, 200, 0.18);
  background: linear-gradient(135deg, #f8fafc 0%, #e0e7ff 100%);
  padding-top: 24px;
}

.el-form {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px 0 rgba(99,102,241,0.06);
  padding: 32px 24px 12px 24px;
  margin-bottom: 0;
}

.el-form-item {
  margin-bottom: 28px;
}

.el-input,
.el-radio-group {
  font-size: 1.08rem;
}

.el-radio {
  margin-right: 24px;
}

.el-button {
  border-radius: 20px;
  font-weight: 500;
  letter-spacing: 1px;
  background: linear-gradient(90deg, #6366f1 0%, #60a5fa 100%);
  color: #fff;
  border: none;
  box-shadow: 0 2px 8px 0 rgba(99,102,241,0.10);
  transition: background 0.2s, box-shadow 0.2s, transform 0.15s;
}
.el-button:hover {
  background: linear-gradient(90deg, #60a5fa 0%, #6366f1 100%);
  box-shadow: 0 4px 16px 0 rgba(99,102,241,0.18);
  transform: scale(1.04);
}

.el-button[type="info"] {
  background: #f1f5f9;
  color: #6366f1;
  border: 1px solid #c7d2fe;
}
.el-button[type="info"]:hover {
  background: #e0e7ff;
  color: #3730a3;
}

.avatar-uploader {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 18px;
}

.avatar-uploader .avatar {
  border-radius: 12px;
  box-shadow: 0 2px 8px 0 rgba(99,102,241,0.10);
  border: 2px solid #e0e7ff;
  object-fit: cover;
}

.editor {
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 1px 4px 0 rgba(99,102,241,0.06);
  background: #f8fafc;
  margin-bottom: 10px;
}

:deep(.ql-toolbar) {
  border-radius: 10px 10px 0 0;
  background: #f1f5f9;
  border: none;
}
:deep(.ql-container) {
  border-radius: 0 0 10px 10px;
  border: none;
  background: #fff;
}

:deep(.ql-editor) {
  font-size: 1.08rem;
  color: #374151;
  min-height: 220px;
}

@media (max-width: 600px) {
  .el-drawer {
    padding: 8px;
  }
  .el-form {
    padding: 12px 4px 4px 4px;
  }
  .editor {
    margin-bottom: 4px;
  }
}

.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
.avatar-uploader {
  :deep {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
.el-alert {
  margin: 20px 0 0;
}
.el-alert:first-child {
  margin: 0;
}
</style>
